<template>
  <div class="comment-container">
    <textarea name id placeholder="请输入评论信息" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="getMsg">发表评论</mt-button>
    <ul class="mui-table-view">
      <li class="mui-table-view-cell mui-media" v-for="(item,i) in contents" :key="item.i">
        <img
          class="mui-media-object mui-pull-left"
          src="https://avatars0.githubusercontent.com/u/42566669?s=40&v=4"
        >
        <div class="mui-media-body">
          <p claass="username">
            <span>{{contents.length-i}} 楼 用户：{{ item.user_name }}</span>
          </p>
          <div class="content">{{ item.content =='undefined' ?'用户没有输入任何内容':item.content }}</div>
          <span class="time">{{ item.add_time | dataFormat }}</span>
        </div>
      </li>
    </ul>

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";

export default {
  data: function() {
    return {
      pageIndex: 1,
      contents: [],
      msg: "" //评论内容
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(result => {
          if (result.body.status === 0) {
            // console.log(result);
            // this.contents = result.body.message;
            // 为了防止数据覆盖----将数组中的内容拼接到一起----
            this.contents = this.contents.concat(result.body.message);
          } else {
            Toast("获取评论失败！");
          }
        },(err)=>{
            Toast('数据加载失败！');
        });
    },
    getMore() {
      this.pageIndex += 1;
      this.getComments();
    },
    getMsg() {
      // 做出一个判断 判断msg中数是否为空
      if (this.msg.trim().length === 0) {
        return Toast("评论内容不能为空！");
      }
      this.$http.post("api/postcomment/" + this.id,{
          content:this.msg.trim()
      }).then(function(result) {
        if (result.body.status === 0) {
          // 评论提交成功 创建一个对象---
           var cmt = {
              user_name: "yaogengzhu",
              add_time: Date.now(),
              content: this.msg.trim()
            };

            // 将这个对象unshift到数组中 
            this.contents.unshift(cmt);

            // 清空输入的内容
            this.msg = '';
        }
      });
    }
  },
  props: ["id"]
};
</script>


<style lang="scss" scoped>
    .comment-container{
        textarea{
            margin:5px 0;
            font-size:12px;
        }
        p{
            padding:0 5px;
            display:flex;
            justify-content:space-between;
        }
        .content{
            margin:10px 0;
            font-size:14px;
        }
        .time{
            font-size:10px;
        }
    }

</style>
